<template>
  <div class="contract-payment">
    <el-card class="table-container">
      <!-- 查询表单 -->
      <el-form :model="state.queryData" inline label-width="90px" @submit.prevent="conditionEnter">
        <el-form-item label="客户">
          <el-input v-model="state.queryData.CustName" placeholder="请输入客户名称" clearable/>
        </el-form-item>
        <el-form-item label="工作号">
          <el-input v-model="state.queryData.JobNum" placeholder="请输入工作号" clearable/>
        </el-form-item>
        <el-form-item label="合同号">
          <el-input v-model="state.queryData.ContractNum" placeholder="请输入合同号" clearable/>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="conditionEnter">查询</el-button>
          <el-button @click="reset">重置</el-button>
          <el-button plain size="default" @click="handleExport">导出</el-button>
          <el-button plain size="default" @click="handleExportFw"  >导出法务审计台账</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <el-card class="table-container">
      <el-table
          :data="state.table.data"
          border
          id="clckexportTab"
          style="width: 100%;height: 600px"
          v-loading="state.loading"
          show-summary
          :summary-method="getSummaries"
          row-key="Id"
      >
        <el-table-column type="selection" width="55" fixed />
        <el-table-column
            v-for="col in state.table.columns"
            :key="col.prop"
            :prop="col.prop"
            :label="col.label"
            :width="col.minWidth"
            show-overflow-tooltip
            :fixed="col.fixed"
        >
          <template v-if="col.slotName" #default="scope">
            <slot :name="col.slotName" :scope="scope">
              <template v-if="col.slotName === 'index'">
                <span>{{scope.$index+1}}</span>
              </template>
              <template v-if="col.slotName === 'IsQc'">
                {{scope.row.IsQc ? '是' : '否'}}
              </template>
              <template v-if="col.slotName === 'File'">
                <el-link type="primary" @click="handleEvent(scope.row)">查看文件</el-link>
              </template>
              <template v-if="col.slotName === 'Ddate'">
                <div>{{ parseTime(scope.row.Ddate, '{y}-{m}-{d}') }}</div>
              </template>

              <template v-if="col.slotName === 'TDYSDate'">
                <div>{{ parseTime(scope.row.TDYSDate, '{y}-{m}-{d}') }}</div>
              </template>
              <template v-if="col.slotName === 'JHYSDate'">
                <div>{{ parseTime(scope.row.JHYSDate, '{y}-{m}-{d}') }}</div>
              </template>
              <template v-if="col.slotName === 'DeliveryDate'">
                <div>{{ parseTime(scope.row.DeliveryDate, '{y}-{m}-{d}') }}</div>
              </template>
              <template v-if="col.slotName === 'SaleDeliveryDate'">
                <div>{{ parseTime(scope.row.SaleDeliveryDate, '{y}-{m}-{d}') }}</div>
              </template>
              <template v-if="col.slotName === 'JSYSDate'">
                <div>{{ parseTime(scope.row.JSYSDate, '{y}-{m}-{d}') }}</div>
              </template>
              <template v-if="col.slotName === 'ChangeLastDate'">
                <div>{{ parseTime(scope.row.ChangeLastDate, '{y}-{m}-{d}') }}</div>
              </template>
              <template v-if="col.slotName === 'ContractAmount'">
                <div>{{ addSeparator(scope.row.ContractAmount) }}</div>
              </template>
              <template v-if="col.slotName === 'ChangedCtAmount'">
                <div>{{ addSeparator(scope.row.ChangedCtAmount) }}</div>
              </template>
              <template v-if="col.slotName === 'FHAmount'">
                <div>{{ addSeparator(scope.row.FHAmount) }}</div>
              </template>
              <template v-if="col.slotName === 'WFHAmount'">
                <div>{{ addSeparator(scope.row.WFHAmount) }}</div>
              </template>
              <template v-if="col.slotName === 'KPAmount'">
                <div>{{ addSeparator(scope.row.KPAmount) }}</div>
              </template>
              <template v-if="col.slotName === 'FHUnKPAmount'">
                <div>{{ addSeparator(scope.row.FHUnKPAmount) }}</div>
              </template>

              <template v-if="col.slotName === 'HKJHAmount'">
                <div>{{ addSeparator(scope.row.HKJHAmount) }}</div>
              </template>
              <template v-if="col.slotName === 'HKAmount'">
                <div>{{ addSeparator(scope.row.HKAmount) }}</div>
              </template>
              <template v-if="col.slotName === 'YSKAmount'">
                <div>{{ addSeparator(scope.row.YSKAmount) }}</div>
              </template>
              <template v-if="col.slotName === 'DQYHKamount'">
                <div>{{ addSeparator(scope.row.DQYHKamount) }}</div>
              </template>
            </slot>
          </template>
          <template v-if="col.children">
            <el-table-column
                v-for="child in col.children"
                :key="child.prop"
                :prop="child.prop"
                :label="child.label"
                :width="child.minWidth"
                show-overflow-tooltip
                :fixed="child.fixed">
              <template v-if="child.slotName" #default="scope">
                <slot :name="child.slotName" :scope="scope">
                  <template v-if="child.slotName === 'HTYDHKSJ'">
                    <div>{{ parseTime(scope.row.HTYDHKSJ, '{y}-{m}-{d}') }}</div>
                  </template>
                  <template v-if="child.slotName === 'DHYDSHJ'">
                    <div>{{ parseTime(scope.row.DHYDSHJ, '{y}-{m}-{d}') }}</div>
                  </template>
                  <template v-if="child.slotName === 'THKDYSJ'">
                    <div>{{ parseTime(scope.row.THKDYSJ, '{y}-{m}-{d}') }}</div>
                  </template>
                  <template v-if="child.slotName === 'YSKHKSJ'">
                    <div>{{ parseTime(scope.row.YSKHKSJ, '{y}-{m}-{d}') }}</div>
                  </template>
                  <template v-if="child.slotName === 'TDYDHKSJ'">
                    <div>{{ parseTime(scope.row.TDYDHKSJ, '{y}-{m}-{d}') }}</div>
                  </template>
                  <template v-if="child.slotName === 'ZBJYDHKSJ'">
                    <div>{{ parseTime(scope.row.ZBJYDHKSJ, '{y}-{m}-{d}') }}</div>
                  </template>
                  <template v-if="child.slotName === 'ZLKDYSJ'">
                    <div>{{ parseTime(scope.row.ZLKDYSJ, '{y}-{m}-{d}') }}</div>
                  </template>
                  <template v-if="child.slotName === 'YXYDHKSJ'">
                    <div>{{ parseTime(scope.row.YXYDHKSJ, '{y}-{m}-{d}') }}</div>
                  </template>
                  <template v-if="child.slotName === 'JSYDHKSJ'">
                    <div>{{ parseTime(scope.row.JSYDHKSJ, '{y}-{m}-{d}') }}</div>
                  </template>
                  <template v-if="child.slotName === 'DYSJYHKAmount'">
                    <div>{{ addSeparator(scope.row.DYSJYHKAmount) }}</div>
                  </template>
                  <template v-if="child.slotName === 'DHSJHKAmount'">
                    <div>{{ addSeparator(scope.row.DHSJHKAmount) }}</div>
                  </template>
                  <template v-if="child.slotName === 'YSKDYSJHKAmount'">
                    <div>{{ addSeparator(scope.row.YSKDYSJHKAmount) }}</div>
                  </template>

                  <template v-if="child.slotName === 'TDDYSJHKAmount'">
                    <div>{{ addSeparator(scope.row.TDDYSJHKAmount) }}</div>
                  </template>

                  <template v-if="child.slotName === 'ZBJDYSJHKAmount'">
                    <div>{{ addSeparator(scope.row.ZBJDYSJHKAmount) }}</div>
                  </template>

                  <template v-if="child.slotName === 'THKAmount'">
                    <div>{{ addSeparator(scope.row.THKAmount) }}</div>
                  </template>

                  <template v-if="child.slotName === 'ZLKAmount'">
                    <div>{{ addSeparator(scope.row.ZLKAmount) }}</div>
                  </template>

                  <template v-if="child.slotName === 'YXDYSJHKAmount'">
                    <div>{{ addSeparator(scope.row.YXDYSJHKAmount) }}</div>
                  </template>

                  <template v-if="child.slotName === 'JSDYSJHKAmount'">
                    <div>{{ addSeparator(scope.row.JSDYSJHKAmount) }}</div>
                  </template>

                </slot>
              </template>

            </el-table-column>
          </template>
        </el-table-column>

      </el-table>

      <el-pagination
          :current-page="state.queryData.PageIndex"
          :page-size="state.queryData.PageSize"
          :total="state.table.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="pageSize"
          @current-change="pageChange"
      />
    </el-card>


    <!-- 用户导入对话框 -->
    <el-dialog
        title="文件查看"
        v-model="state.fileOpen"
        width="800px"
        append-to-body
        :close-on-click-modal="false"
    >
      <el-table :data="state.dataList"  border  >
        <el-table-column label="文件名称" prop="FileName" width="200"></el-table-column>
        <el-table-column label="文件类型" prop="JDType" width="100"></el-table-column>
        <el-table-column label="上传时间" prop="CreateDate" width="300">
          <template #default="scope">
            <div>{{ parseTime(scope.row.CreateDate, '{y}-{m}-{d} {h}:{i}:{s}') }}</div>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template #default="scope">
            <el-button type="primary" @click="handleOpenFile(scope.row)">查看文件</el-button>
          </template>
        </el-table-column>

      </el-table>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="closeFile">关 闭</el-button>
        </div>
      </template>
    </el-dialog>

  </div>
</template>

<script setup lang="tsx">
import {userRole,GetTZData} from "@/api/base"
import {computed, reactive, ref, toRefs,onMounted} from "vue"
import {contractReport,GetSJHTTZReport} from "@/api/contract_entry"
import {parseTime,checkPermission,addSeparator} from "@/utils/util";
import download from "@/utils/download";
import {cubasdocStore} from "@/stores/modules/cubasdoc";
import FileSaver from "file-saver";
import XLSX from "xlsx";
import { VxeTable, VxeColumn } from 'vxe-table'
import 'vxe-table/lib/style.css'

const tAdaptivePageRef: any = ref(null)

const cubasdoc = cubasdocStore()
//表格配置
const state: any = reactive({
  roleList: [],
  queryData: {
    CustCode: null,
    ContractNum: null,
    CustName: null,
  },
  table: {
    border: true,
    // 接口返回数据
    data: [],
    // 表头数据
    columns: [
      { prop: "LineNum", label: "序号", minWidth: 60, slotName: 'index',fixed: 'left' },
      { prop: "JobNum", label: "工作号", minWidth: 110,fixed: 'left'  },
      { prop: "File", label: "文件", minWidth: 110,slotName: 'File' },
      { prop: "ContractNum", label: "合同号", minWidth: 160 },
      { prop: "ContractName", label: "合同名称", minWidth: 120 },
      { prop: "salename", label: "销售员", minWidth: 90},
      { prop: "state", label: "合同状态",minWidth: 110},
      { prop: "IsQc", label: "是否期初",minWidth: 90,slotName: 'IsQc'},
      { prop: "Ddate", label: "合同签订日期", minWidth: 120,slotName:'Ddate' },
      { prop: "CustName", label: "客户名称", minWidth: 140},
      { prop: "ProjectName", label: "项目名称", minWidth: 100},
      { prop: "ContractAmount", label: "合同金额(元)", minWidth: 130,slotName: 'ContractAmount'},
      { prop: "ChangedCtAmount", label: "变更合同最后签订金额(元)", minWidth: 130,slotName: 'ChangedCtAmount'},
      { prop: "DeliveryDate", label: "合同签订交货日期", minWidth: 100,slotName:'DeliveryDate' },
      { prop: "ChangelastDate", label: "变更合同最后签订交期", minWidth: 100,slotName: 'ChangeLastDate' },
      { prop: "ZLQSQK", label: "资料缺失情况", minWidth: 110},
      { prop: "tdysfj", label: "通电验收资料", minWidth: 110},
      { prop: "jhysfj", label: "交货验收资料", minWidth: 110},
      { prop: "jszlfj", label: "结算资料", minWidth: 110},
      { prop: "yszlfj", label: "预收资料", minWidth: 110},

      { prop: "Remark", label: "合同情况备注", minWidth: 100 },

      { prop: "FHAmount", label: "已发货金额(元)", minWidth: 130,slotName: 'FHAmount' },
      { prop: "WFHAmount", label: "未发货金额(元)", minWidth: 130,slotName: 'WFHAmount' },
      { prop: "KPAmount", label: "开票金额(元)", minWidth: 130,slotName: 'KPAmount' },
      { prop: "Rate", label: "税率", minWidth: 120 },

      { prop: "FHUnKPAmount", label: "发货未开票金额(元)", minWidth: 130,slotName: 'FHUnKPAmount' },
      { prop: "YFHWKPYY", label: "已发货未开票原因", minWidth: 100},
      { prop: "HKJHAmount", label: "计算到期的合同应收款计划金额(元)", minWidth: 130,slotName: 'HKJHAmount'},
      { prop: "HKAmount", label: "实际回款总额(元)", minWidth: 130,slotName: 'HKAmount'},
      { prop: "HKRatio", label: "计算回款比列", minWidth: 100,},
      { prop: "YSKAmount", label: "计算财务应收款余额(元)", minWidth: 130,slotName: 'YSKAmount'},
      { prop: "DQYHKamount", label: "计算到期的合同应收款余额(元)", minWidth: 130,slotName: 'DQYHKamount'},

      { prop: "YFK", label: "第一阶段：预付款", minWidth: 300,children: [
          { prop: "YFKYDBL", label: "合同约定比例", minWidth: 100 },
          { prop: "HTYDHKSJ", label: "合同约定回款时间", minWidth: 100,slotName: 'HTYDHKSJ' },
          { prop: "DYSJYHKAmount", label: "对应时间应回款金额", minWidth: 130,slotName: 'DYSJYHKAmount' },
        ] },
      { prop: "ZLK", label: "第二阶段：资料款", minWidth: 300,children: [
          { prop: "ZLKBLAmount", label: "合同约定比例", minWidth: 100 },
          { prop: "ZLKDYSJ", label: "合同约定回款时间", minWidth: 100,slotName: 'ZLKDYSJ' },
          { prop: "ZLKAmount", label: "对应时间应回款金额", minWidth: 130,slotName: 'ZLKAmount' },
        ]
      },

      { prop: "THK", label: "第三阶段：提货款", minWidth: 300,children: [
          { prop: "THKBLAmount", label: "合同约定比例", minWidth: 100 },
          { prop: "THKDYSJ", label: "合同约定回款时间", minWidth: 100,slotName: 'THKDYSJ' },
          { prop: "THKAmount", label: "对应时间应回款金额", minWidth: 130,slotName: 'THKAmount' },
        ]
      },
      { prop: "DHK", label: "第四阶段：到货款", minWidth: 300,children: [
          { prop: "DHBLAmount", label: "合同约定比例", minWidth: 100 },
          { prop: "DHYDSHJ", label: "合同约定回款时间", minWidth: 100,slotName: 'DHYDSHJ' },
          { prop: "DHSJHKAmount", label: "对应时间应回款金额", minWidth: 130,slotName: 'DHSJHKAmount' },
        ]
      },
      { prop: "YSK", label: "第五阶段：验收进度款", minWidth: 300,children: [
          { prop: "YSKBLAmount", label: "合同约定比例", minWidth: 100 },
          { prop: "YSKHKSJ", label: "合同约定回款时间", minWidth: 100,slotName: 'YSKHKSJ' },
          { prop: "YSKDYSJHKAmount", label: "对应时间应回款金额", minWidth: 120,slotName: 'YSKDYSJHKAmount' },
        ]
      },

      { prop: "TDK", label: "第六阶段：通电款", minWidth: 300,children: [
          { prop: "TDYDBL", label: "合同约定比例", minWidth: 100 },
          { prop: "TDYDHKSJ", label: "合同约定回款时间", minWidth: 100,slotName: 'TDYDHKSJ' },
          { prop: "TDDYSJHKAmount", label: "对应时间应回款金额", minWidth: 130,slotName: 'TDDYSJHKAmount' },
        ]
      },

      { prop: "YXK", label: "第七阶段：运行款", minWidth: 300,children: [
          { prop: "YXYDBL", label: "合同约定比例", minWidth: 100 },
          { prop: "YXYDHKSJ", label: "合同约定回款时间", minWidth: 100,slotName: 'YXYDHKSJ' },
          { prop: "YXDYSJHKAmount", label: "对应时间应回款金额", minWidth: 130,slotName: 'YXDYSJHKAmount' },
        ]
      },

      { prop: "YSK", label: "第八阶段：结算款", minWidth: 300,children: [
          { prop: "JSYDBL", label: "合同约定比例", minWidth: 100 },
          { prop: "JSYDHKSJ", label: "合同约定回款时间", minWidth: 100,slotName: 'JSYDHKSJ' },
          { prop: "JSDYSJHKAmount", label: "对应时间应回款金额", minWidth: 130,slotName: 'JSDYSJHKAmount' },
        ]
      },

      { prop: "ZBJ", label: "第九阶段：质保金", minWidth: 300,children: [

          { prop: "ZBJHTYDBL", label: "质保金（合同约定比例）", minWidth: 150 },
          { prop: "ZBJYDHKSJ", label: "合同约定回款时间", minWidth: 100,slotName: 'ZBJYDHKSJ' },
          { prop: "ZBJDYSJHKAmount", label: "对应时间应回款金额", minWidth: 130,slotName: 'ZBJDYSJHKAmount' }
        ]
      },


    ],
  },
  loading:false,
  isShowSubBut:true,
  isBg:false,
  title: "新增合同录入",
  dialogSelectEnt:false,
  dataList:[],
  fileOpen:false
})

//表单配置
const opts = ref({

  CustCode: {
    label: "客户",
    placeholder: "请输入客户信息",
    comp: "el-input"
  },
  ContractNum: {
    label: "合同编码",
    comp: "el-input"
  },

  CreateFrom: {
    label: "制单日期",
    comp: "t-date-picker",
    span: 1,
    bind: {
      type: "daterange"
    }
  },


})

//选择项
const cusoptions = ref([])

// 最终参数获取
const getQueryData = computed(() => {
  const data = toRefs(state.queryData)
  //转换查询参数
  return {
    JobNum: data.JobNum?.value,
    CustCode: data.CustCode?.value,
    ContractNum: data.ContractNum?.value,
    CustName: data.CustName?.value,
    CreateFrom: data.CreateFrom?.value && data.CreateFrom?.value[0] ? data.CreateFrom?.value[0] : null,
    CreateTo: data.CreateFrom?.value && data.CreateFrom?.value[1] ? data.CreateFrom?.value[1] : null,
  }
})


// 点击查询按钮
const reset = () => {
  state.queryData={
    CustCode: null,
    ContractNum: null,
    CustName: null,
    JobNum: null,
  }
  getData(1)
}

// 点击查询按钮
const conditionEnter = () => {
  getData(1)
}


const pageSize = val => {

  state.table.pageSize = val
  getData(val)
}

// 选择当前页码
const pageChange = val => {

  state.table.currentPage = val
  getData(val)
}

// 获取数据
const getData = async pageNum => {
  state.loading = true
  let data=await contractReport(getQueryData.value);

  if (data.Code==='OK'){
    state.table.data = data.Data
    state.table.total = data.Count
  }
  state.loading = false
}

onMounted(() => {
   getData(1)
  initRoleList()
})


//过滤单位
const cnvbasdocMethod = (query) => {
  if (query) {
    state.loading = true
    setTimeout(() => {
      state.loading = false

      cusoptions.value = cubasdoc.data.filter((its) => {
        return (its.cCusCode.toLowerCase().includes(query.toLowerCase()) || its.ccusabbname.toLowerCase().includes(query.toLowerCase()))
      })
    }, 200)
  } else {
    cusoptions.value = []
  }
}

function handleExport(fileName='',idName = "#clckexportTab",xlsxParam={ raw: true }){
  let wb = XLSX.utils.table_to_book(
      document.querySelector(idName),
      xlsxParam
  );
  let wbout = XLSX.write(wb, {
    bookType: "xlsx",
    bookSST: true,
    type: "array",
  });
  try {
    FileSaver.saveAs(
        new Blob([wbout], { type: "application/octet-stream" }),
        `合同汇总表.xlsx`
    );
  } catch (e) {
  }
  return wbout;
}

//导出指定台账
async function handleExportFw() {
  let data = await GetSJHTTZReport(getQueryData.value);
  download(data,"法务合同台账.xlsx")
}



const initRoleList = async () => {
  let res = await userRole({ VT_ID: '合同台账' })
  state.roleList = res.items
}


// ... existing code ...
const handleEvent = async(row) => {
  // 文件列表
  let axiosResponse = await GetTZData({ id: row.Id });
  let dataList = axiosResponse.Data
  // 清空之前的文件列表
  state.dataList = [];

  dataList.forEach(item => {
    //初始化文件
    if (item.TDYS){
      let tdysFiles = item.TDYS.filter((its) => {
        return (its.FileAdd != null && its.FileAdd != '')
      })
      state.dataList = state.dataList.concat(tdysFiles)
    }
    if (item.FHYS){
      let fhysFiles = item.FHYS.filter((its) => {
        return (its.FileAdd != null && its.FileAdd != '')
      })
      state.dataList = state.dataList.concat(fhysFiles)
    }
    if (item.JSYS){
      let jsysFiles = item.JSYS.filter((its) => {
        return (its.FileAdd != null && its.FileAdd != '')
      })
      state.dataList = state.dataList.concat(jsysFiles)
    }
  })
  state.fileOpen = true
}

const handleOpenFile = async (data) => {
  window.open(import.meta.env.VITE_APP_BASE_API + '/' + data.FileAdd)
}


const closeFile = async () => {
  state.fileOpen = false
  state.dataList = []
}

const getSummaries = param => {
  const { columns, data } = param
  const sums = []
  columns.forEach((column, index) => {
    if (index === 0) {
      sums[index] = '合计'
      return
    }


    if (![12,13,18,19,20,22,24,25,27,28,31,34,37,40,43,46,49,52,55].includes(index)) {
      sums[index] = ''
      return
    }

    const values = data.map(item => Number(item[column.property]))
    if (!values.every(value => isNaN(value))) {
      sums[index] = addSeparator(values.reduce((prev, curr) => {
        const value = Number(curr)
        if (!isNaN(value)) {
          return prev + curr
        } else {
          return prev
        }
      }, 0))
      sums[index] += ''
    } else {
      sums[index] = 'N/A'
    }
  })

  return sums
}


</script>
